import './index.css'
import { Tag, Space } from 'antd'
import { useSelector, useDispatch } from 'react-redux'
import { useLocation, useNavigate } from 'react-router-dom'
import { removeMenuList } from '../../store/reducers/tab.js'
import { useState } from 'react'

const CommonTag = () => {
  let location = useLocation()
  let navigate = useNavigate()
  let dispatch = useDispatch()
  const tabList = useSelector((state) => state.tab.tabList)
  // 记录hoverIndex
  let [hoverIndex, setHoverIndex] = useState(-1)
  // 点击关闭标签
  const handleClose = (val, index) => {
    // 判断关闭的tag是不是当前所在的tag
    if (location.pathname !== val.path) {
      dispatch(removeMenuList(val))
    }
    // 获取当前的下一个数据
    let nextTab = ''
    // 更新tabList
    if (tabList[index + 1]) {
      nextTab = tabList[index + 1]
    } else {
      nextTab = tabList[index - 1]
    }
    dispatch(removeMenuList(val))
    console.log(nextTab.path)
    navigate(nextTab.path)
  }
  // 点击选中标签,进行页面跳转
  const handleSelect = (val) => {
    navigate(val.path)
  }
  return (
    <Space size={[0, 8]} className='tag-container'>
      {tabList.map((item, index) => {
        // console.dir(item)
        // console.log(location.pathname)
        return (
          <Tag
            key={item.path}
            onMouseEnter={() => setHoverIndex(index)}
            onMouseLeave={() => setHoverIndex(-1)}
            onClick={() => handleSelect(item)}
            color={
              location.pathname === item.path ||
              (location.pathname === '/home' && item.label === '首页')
                ? '#55acee'
                : ''
            }
            closeIcon={location.pathname === item.path || hoverIndex === index}
            onClose={() => handleClose(item, index)}>
            {item.label}
          </Tag>
        )
      })}
    </Space>
  )
}

export default CommonTag
